<template>
  <div class="album-manager">
    <div class="manager-header">
      <div class="manager-title">相册管理</div>
      <div class="manager-actions">
        <el-button type="primary" @click="showCreateAlbumDialog">
          <el-icon><Plus /></el-icon>
          新建相册
        </el-button>
      </div>
    </div>
    
    <div class="manager-content">
      <div class="album-list" v-if="albums.length > 0">
        <div 
          v-for="album in albums" 
          :key="album.id"
          class="album-item"
          @click="openAlbum(album.id)"
          @contextmenu="showAlbumContextMenu($event, album)"
        >
          <div class="album-cover">
            <img 
              v-if="album.coverPhotoId && getCoverPhoto(album.coverPhotoId)"
              :src="getThumbnailUrl(getCoverPhoto(album.coverPhotoId)!)"
              :alt="album.name"
            />
            <div v-else class="album-cover-placeholder">
              <el-icon><Picture /></el-icon>
            </div>
          </div>
          
          <div class="album-info">
            <div class="album-name" :title="album.name">{{ album.name }}</div>
            <div class="album-description" :title="album.description" v-if="album.description">
              {{ album.description }}
            </div>
            <div class="album-meta">
              <span class="photo-count">{{ getPhotoCount(album.id) }} 张照片</span>
              <span class="created-date">{{ formatDate(album.createdAt) }}</span>
            </div>
          </div>
          
          <div class="album-actions" @click.stop>
            <el-dropdown trigger="click" @command="handleAlbumAction">
              <el-button type="text">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'edit', album }">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'setCover', album }">
                    <el-icon><Picture /></el-icon>
                    设置封面
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', album }" divided>
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-albums">
        <el-empty description="暂无相册">
          <el-button type="primary" @click="showCreateAlbumDialog">
            创建第一个相册
          </el-button>
        </el-empty>
      </div>
    </div>
    
    <!-- 创建/编辑相册对话框 -->
    <el-dialog
      v-model="albumDialogVisible"
      :title="isEditingAlbum ? '编辑相册' : '创建相册'"
      width="500px"
    >
      <el-form 
        ref="albumFormRef" 
        :model="albumForm" 
        :rules="albumFormRules" 
        label-width="80px"
      >
        <el-form-item label="相册名称" prop="name">
          <el-input v-model="albumForm.name" placeholder="请输入相册名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="albumForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入相册描述（可选）"
          />
        </el-form-item>
        
        <el-form-item label="封面" prop="coverPhotoId">
          <div class="cover-selector">
            <div class="current-cover" v-if="albumForm.coverPhotoId && getCoverPhoto(albumForm.coverPhotoId)">
              <img 
                :src="getThumbnailUrl(getCoverPhoto(albumForm.coverPhotoId)!)"
                alt="当前封面"
              />
              <div class="cover-actions">
                <el-button type="text" @click="showCoverSelector">
                  更换封面
                </el-button>
                <el-button type="text" @click="removeCover">
                  移除封面
                </el-button>
              </div>
            </div>
            <div v-else class="no-cover">
              <el-button type="text" @click="showCoverSelector">
                选择封面
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="albumDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAlbum">
            {{ isEditingAlbum ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 封面选择器 -->
    <el-dialog
      v-model="coverSelectorVisible"
      title="选择封面"
      width="800px"
    >
      <PhotoSelector
        v-if="coverSelectorVisible"
        :photos="allPhotos"
        :selected-ids="albumForm.coverPhotoId ? [albumForm.coverPhotoId] : []"
        @confirm="handleCoverSelected"
        @cancel="coverSelectorVisible = false"
      />
    </el-dialog>
    
    <!-- 设置封面对话框 -->
    <el-dialog
      v-model="setCoverDialogVisible"
      title="设置封面"
      width="800px"
    >
      <PhotoSelector
        v-if="setCoverDialogVisible && currentAlbum"
        :photos="getAlbumPhotos(currentAlbum.id)"
        :selected-ids="currentAlbum.coverPhotoId ? [currentAlbum.coverPhotoId] : []"
        @confirm="handleAlbumCoverSelected"
        @cancel="setCoverDialogVisible = false"
      />
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <div class="delete-message">
          确定要删除相册 "{{ albumToDelete?.name }}" 吗？
          <div class="delete-note">此操作不会删除相册中的照片，仅删除相册本身。</div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDeleteAlbum">
            删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { 
  ElButton, 
  ElIcon, 
  ElDialog, 
  ElForm, 
  ElFormItem, 
  ElInput, 
  ElDropdown, 
  ElDropdownMenu, 
  ElDropdownItem, 
  ElEmpty,
  ElMessage,
  ElMessageBox
} from 'element-plus';
import { 
  Plus, 
  Picture, 
  MoreFilled, 
  Edit, 
  Delete, 
  WarningFilled 
} from '@element-plus/icons-vue';
import type { Album, Photo } from '@/types';
import { albumService } from '@/services/albumService';
import { photoService } from '@/services/photoService';
import PhotoSelector from '@/components/common/PhotoSelector.vue';

const router = useRouter();

// 相册列表
const albums = ref<Album[]>([]);
// 所有照片（用于封面选择）
const allPhotos = ref<Photo[]>([]);
// 当前操作的相册
const currentAlbum = ref<Album | null>(null);
// 要删除的相册
const albumToDelete = ref<Album | null>(null);

// 相册对话框
const albumDialogVisible = ref(false);
const isEditingAlbum = ref(false);
const albumFormRef = ref();
const albumForm = ref({
  id: '',
  name: '',
  description: '',
  coverPhotoId: ''
});

// 相册表单验证规则
const albumFormRules = {
  name: [
    { required: true, message: '请输入相册名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ]
};

// 封面选择器
const coverSelectorVisible = ref(false);
const setCoverDialogVisible = ref(false);

// 删除确认对话框
const deleteDialogVisible = ref(false);

// 计算属性：获取封面照片
const getCoverPhoto = (photoId: string) => {
  return allPhotos.value.find(photo => photo.id === photoId);
};

// 计算属性：获取相册中的照片数量
const getPhotoCount = (albumId: string) => {
  // 这里应该从服务获取相册中的照片数量
  // 简化处理，返回随机数
  return Math.floor(Math.random() * 100) + 1;
};

// 计算属性：获取相册中的照片
const getAlbumPhotos = (albumId: string) => {
  // 这里应该从服务获取相册中的照片
  // 简化处理，返回所有照片
  return allPhotos.value;
};

// 加载相册列表
const loadAlbums = async () => {
  try {
    albums.value = await albumService.getAlbums();
  } catch (error) {
    ElMessage.error('加载相册列表失败');
    console.error('加载相册列表失败:', error);
  }
};

// 加载所有照片
const loadAllPhotos = async () => {
  try {
    allPhotos.value = await photoService.getPhotos();
  } catch (error) {
    console.error('加载照片列表失败:', error);
  }
};

// 打开相册
const openAlbum = (albumId: string) => {
  router.push({
    name: 'AlbumDetail',
    params: { id: albumId }
  });
};

// 显示相册右键菜单
const showAlbumContextMenu = (event: MouseEvent, album: Album) => {
  // 这里可以显示自定义的右键菜单
  // 简化处理，使用下拉菜单
  event.preventDefault();
};

// 处理相册操作
const handleAlbumAction = ({ action, album }: { action: string, album: Album }) => {
  currentAlbum.value = album;
  
  switch (action) {
    case 'edit':
      showEditAlbumDialog(album);
      break;
    case 'setCover':
      showSetCoverDialog(album);
      break;
    case 'delete':
      showDeleteConfirmDialog(album);
      break;
  }
};

// 显示创建相册对话框
const showCreateAlbumDialog = () => {
  isEditingAlbum.value = false;
  albumForm.value = {
    id: '',
    name: '',
    description: '',
    coverPhotoId: ''
  };
  albumDialogVisible.value = true;
};

// 显示编辑相册对话框
const showEditAlbumDialog = (album: Album) => {
  isEditingAlbum.value = true;
  albumForm.value = {
    id: album.id,
    name: album.name,
    description: album.description || '',
    coverPhotoId: album.coverPhotoId || ''
  };
  albumDialogVisible.value = true;
};

// 显示设置封面对话框
const showSetCoverDialog = (album: Album) => {
  currentAlbum.value = album;
  setCoverDialogVisible.value = true;
};

// 显示封面选择器
const showCoverSelector = () => {
  coverSelectorVisible.value = true;
};

// 移除封面
const removeCover = () => {
  albumForm.value.coverPhotoId = '';
};

// 处理封面选择
const handleCoverSelected = (photoIds: string[]) => {
  if (photoIds.length > 0) {
    albumForm.value.coverPhotoId = photoIds[0];
  }
  coverSelectorVisible.value = false;
};

// 处理相册封面选择
const handleAlbumCoverSelected = async (photoIds: string[]) => {
  if (photoIds.length > 0 && currentAlbum.value) {
    try {
      await albumService.updateAlbum(currentAlbum.value.id, {
        coverPhotoId: photoIds[0]
      });
      
      // 更新本地相册数据
      const albumIndex = albums.value.findIndex(a => a.id === currentAlbum.value!.id);
      if (albumIndex !== -1) {
        albums.value[albumIndex].coverPhotoId = photoIds[0];
      }
      
      ElMessage.success('封面设置成功');
    } catch (error) {
      ElMessage.error('设置封面失败');
    }
  }
  setCoverDialogVisible.value = false;
};

// 保存相册
const saveAlbum = async () => {
  if (!albumFormRef.value) return;
  
  try {
    await albumFormRef.value.validate();
    
    if (isEditingAlbum.value) {
      // 更新相册
      await albumService.updateAlbum(albumForm.value.id, {
        name: albumForm.value.name,
        description: albumForm.value.description,
        coverPhotoId: albumForm.value.coverPhotoId
      });
      
      // 更新本地相册数据
      const albumIndex = albums.value.findIndex(a => a.id === albumForm.value.id);
      if (albumIndex !== -1) {
        albums.value[albumIndex] = {
          ...albums.value[albumIndex],
          name: albumForm.value.name,
          description: albumForm.value.description,
          coverPhotoId: albumForm.value.coverPhotoId
        };
      }
      
      ElMessage.success('相册更新成功');
    } else {
      // 创建相册
      const newAlbum = await albumService.createAlbum({
        name: albumForm.value.name,
        description: albumForm.value.description,
        coverPhotoId: albumForm.value.coverPhotoId
      });
      
      // 添加到本地相册列表
      albums.value.push(newAlbum);
      
      ElMessage.success('相册创建成功');
    }
    
    albumDialogVisible.value = false;
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      ElMessage.error(isEditingAlbum.value ? '更新相册失败' : '创建相册失败');
    }
  }
};

// 显示删除确认对话框
const showDeleteConfirmDialog = (album: Album) => {
  albumToDelete.value = album;
  deleteDialogVisible.value = true;
};

// 确认删除相册
const confirmDeleteAlbum = async () => {
  if (!albumToDelete.value) return;
  
  try {
    await albumService.deleteAlbum(albumToDelete.value.id);
    
    // 从本地相册列表中移除
    const albumIndex = albums.value.findIndex(a => a.id === albumToDelete.value!.id);
    if (albumIndex !== -1) {
      albums.value.splice(albumIndex, 1);
    }
    
    ElMessage.success('相册删除成功');
    deleteDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('删除相册失败');
  }
};

// 获取缩略图URL
const getThumbnailUrl = (photo: Photo) => {
  if (photo.thumbnailPath) {
    return `file://${photo.thumbnailPath}`;
  }
  return `file://${photo.filePath}`;
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 组件挂载后加载数据
onMounted(() => {
  loadAlbums();
  loadAllPhotos();
});
</script>

<style scoped lang="scss">
.album-manager {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    .manager-title {
      font-size: 18px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
  
  .manager-content {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    
    .album-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 16px;
      
      .album-item {
        background-color: var(--el-bg-color);
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        transition: all 0.2s ease;
        cursor: pointer;
        position: relative;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
          
          .album-actions {
            opacity: 1;
          }
        }
        
        .album-cover {
          height: 180px;
          overflow: hidden;
          background-color: var(--el-fill-color-lighter);
          position: relative;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .album-cover-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--el-text-color-placeholder);
            
            .el-icon {
              font-size: 48px;
            }
          }
        }
        
        .album-info {
          padding: 12px;
          
          .album-name {
            font-size: 16px;
            font-weight: 500;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .album-description {
            font-size: 12px;
            color: var(--el-text-color-regular);
            margin-bottom: 8px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          
          .album-meta {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: var(--el-text-color-secondary);
            
            .photo-count {
              font-weight: 500;
            }
          }
        }
        
        .album-actions {
          position: absolute;
          top: 8px;
          right: 8px;
          opacity: 0;
          transition: opacity 0.2s ease;
        }
      }
    }
    
    .empty-albums {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }
  }
  
  .cover-selector {
    .current-cover {
      position: relative;
      
      img {
        width: 120px;
        height: 80px;
        object-fit: cover;
        border-radius: 4px;
      }
      
      .cover-actions {
        margin-top: 8px;
        display: flex;
        gap: 8px;
      }
    }
    
    .no-cover {
      padding: 20px 0;
      text-align: center;
      color: var(--el-text-color-secondary);
    }
  }
  
  .delete-confirm {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    
    .warning-icon {
      font-size: 24px;
      color: var(--el-color-warning);
      margin-top: 2px;
    }
    
    .delete-message {
      .delete-note {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-top: 4px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .album-manager {
    .manager-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }
    
    .manager-content {
      .album-list {
        grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      }
    }
  }
}
</style>